#include "weather.h"
// #include "menu.h"
#include "ui_weather.h"

weather::weather(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::weather)
{
    ui->setupUi(this);
    //重新创一个库用来存储我关注的城市的信息
    cityDatabase = new MyDatabase("city.db","city");
    //定义一个创建表格的SQL语句
    QString str = "create table IF NOT EXISTS city(\
            id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
            cityname varchar(255),\
            cityid varchar(255)\
       )";
    //执行一个SQL语句
    cityDatabase->execSql(str);

    vFore = new QVector<forecast>;
    Manager = new QNetworkAccessManager(this);//创建一个网络管理者
    connect(Manager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(QNetworkReply *)));
    connect(this,SIGNAL(finishedparse()),this , SLOT(weathershowSlot()));
    connect(this,SIGNAL(finishedfollow()),this , SLOT(comboxshow()));
    // connect(gameui->weatherlabel,SIGNAL(doubleClicked(QWidget*)),this,SLOT(on_weatherlabel_widgetshow(QWidget *)));
    comboxshow();
}

weather::~weather()
{
    delete ui;
}

void weather::parsejson(QByteArray &byteArr)
{
    //从JSON字符串构建一个JSON文档
    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArr);
    //询问JSON文档是否是一个对象
    if(jsonDoc.isObject())
    {
        //把JSON文档转为JSON对象，这样就可以访问对象里面的关键字
        QJsonObject jsonObj = jsonDoc.object();
        //如果对象是cityinfo关键字
        if(jsonObj.contains("cityInfo"))
        {
            //既然包含cityinfo，就可以获得cityinfo的值
            QJsonValue val1 = jsonObj.value("cityInfo");
            //问value是否是一个JSON对象
            if(val1.isObject())
            {
                // cityinfo ct;
                //把cityinfo的值转为JSON对象
                QJsonObject objC = val1.toObject();
                if(objC.contains("city"))
                {
                    QJsonValue val = objC.value("city");
                    ct.city = val.toString();
                }
                if(objC.contains("citykey"))
                {
                    QJsonValue val = objC.value("citykey");
                    ct.citykey = val.toString();
                }
                if(objC.contains("parent"))
                {
                    QJsonValue val = objC.value("parent");
                    ct.parent = val.toString();
                    ui->label_3->setText(ct.city);
                    ui->label_8->setText(ct.parent);
                }
                if(objC.contains("updateTime"))
                {
                    QJsonValue val = objC.value("updateTime");
                    ct.updatetime = val.toString();
                }
            }
        }
        if(jsonObj.contains("data"))
        {
            QJsonValue val2 = jsonObj.value("data");
            //问value是否是一个对象
            if(val2.isObject())
            {
                // airindex air;
                //把data的值转为JSON对象
                QJsonObject objD = val2.toObject();
                if(objD.contains("shidu"))
                {
                    QJsonValue valshi = objD.value("shidu");
                    air.shidu = valshi.toString();
                    ui->shidu->setText(air.shidu);
                }
                if(objD.contains("pm25"))
                {
                    QJsonValue valp25 = objD.value("pm25");
                    air.pm25 = valp25.toDouble();
                    ui->pm25->setText(QString("%1").arg(air.pm25));
                }
                if(objD.contains("pm10"))
                {
                    QJsonValue valp10 = objD.value("pm10");
                    air.pm10 = valp10.toDouble();
                    ui->pm10->setText(QString("%1").arg(air.pm10));
                }
                if(objD.contains("quality"))
                {
                    QJsonValue valq = objD.value("quality");
                    // air[0]->quality = valq.toString();
                }
                if(objD.contains("wendu"))
                {
                    QJsonValue valw = objD.value("wendu");
                    air.wendu = valw.toString();
                    ui->wendu->setText(air.wendu+"℃");
                }
                if(objD.contains("ganmao"))
                {
                    QJsonValue valg = objD.value("ganmao");
                    // air[0]->warn = valg.toString();
                }
                if(objD.contains("forecast"))
                {
                    QJsonValue valfore = objD.value("forecast");
                    if(valfore.isArray())
                    {
                        QJsonArray arrFore = valfore.toArray();
                        for(int i = 0;i<arrFore.size();i++)
                        {
                            forecast fore;
                            if(arrFore[i].isObject())
                            {
                                QJsonObject elmF = arrFore[i].toObject();
                                if(elmF.contains("date"))
                                {
                                    QJsonValue vald = elmF.value("date");
                                    fore.date = vald.toString();
                                }
                                if(elmF.contains("high"))
                                {
                                    QJsonValue valh = elmF.value("high");
                                    QString str = valh.toString();
                                    fore.high = conversion(&str);
                                }
                                if(elmF.contains("low"))
                                {
                                    QJsonValue vall = elmF.value("low");
                                    QString str = vall.toString();
                                    fore.low = conversion(&str);
                                }
                                if(elmF.contains("ymd"))
                                {
                                    QJsonValue valy = elmF.value("ymd");
                                    fore.ymd = valy.toString();
                                }
                                if(elmF.contains("week"))
                                {
                                    QJsonValue valw = elmF.value("week");
                                    fore.week = valw.toString();
                                }
                                if(elmF.contains("sunrise"))
                                {
                                    QJsonValue valsr = elmF.value("sunrise");
                                    fore.sunrise = valsr.toString();
                                }
                                if(elmF.contains("sunset"))
                                {
                                    QJsonValue valss = elmF.value("sunset");
                                    fore.sunset = valss.toString();
                                }
                                if(elmF.contains("aqi"))
                                {
                                    QJsonValue valaqi = elmF.value("aqi");
                                    fore.aqi = valaqi.toDouble();
                                }
                                if(elmF.contains("fx"))
                                {
                                    QJsonValue valfx = elmF.value("fx");
                                    fore.fx = valfx.toString();
                                }
                                if(elmF.contains("fl"))
                                {
                                    QJsonValue valfl = elmF.value("fl");
                                    fore.fl = valfl.toString();
                                }
                                if(elmF.contains("type"))
                                {
                                    QJsonValue valtype = elmF.value("type");
                                    fore.type = valtype.toString();
                                }
                                if(elmF.contains("notice"))
                                {
                                    QJsonValue valnotice = elmF.value("notice");
                                    fore.notice = valnotice.toString();
                                }
                            }
                            vFore->push_back(fore);
                        }
                    }
                }
                if(objD.contains("yesterday"))
                {
                    QJsonValue valyes = objD.value("yesterday");
                    if(valyes.isObject())
                    {
                        forecast forey;
                        QJsonObject objY = valyes.toObject();
                        if(objY.contains("date"))
                        {
                            QJsonValue val = objY.value("date");
                            forey.date = val.toString();
                        }
                        if(objY.contains("high"))
                        {
                            QJsonValue val = objY.value("high");
                            QString str = val.toString();
                            forey.high = conversion(&str);
                        }
                        if(objY.contains("low"))
                        {
                            QJsonValue val = objY.value("low");
                            QString str = val.toString();
                            forey.high = conversion(&str);
                        }
                        if(objY.contains("ymd"))
                        {
                            QJsonValue val = objY.value("ymd");
                            forey.ymd = val.toString();
                        }
                        if(objY.contains("week"))
                        {
                            QJsonValue val = objY.value("week");
                            forey.date = val.toString();
                        }
                        if(objY.contains("sunrise"))
                        {
                            QJsonValue val = objY.value("sunrise");
                            forey.sunrise = val.toString();
                        }
                        if(objY.contains("sunset"))
                        {
                            QJsonValue val = objY.value("sunset");
                            forey.sunset = val.toString();
                        }
                        if(objY.contains("aqi"))
                        {
                            QJsonValue val = objY.value("aqi");
                            forey.aqi = val.toDouble();
                        }
                        if(objY.contains("fx"))
                        {
                            QJsonValue val = objY.value("fx");
                            forey.fx = val.toString();
                        }
                        if(objY.contains("fl"))
                        {
                            QJsonValue val = objY.value("fl");
                            forey.fl = val.toString();
                        }
                        if(objY.contains("type"))
                        {
                            QJsonValue val = objY.value("type");
                            forey.type = val.toString();
                        }
                        if(objY.contains("notice"))
                        {
                            QJsonValue val = objY.value("notice");
                            forey.notice = val.toString();
                        }
                        vFore->push_back(forey);
                        // qDebug() << vFore->at(0).notice;
                    }
                }
            }
        }
    }
    emit finishedparse();
}

//查找城市id号
QString weather::findCityid(QString *str)
{
    str->replace("市","");
    // QStringList code;//用于存储所有匹配的城市id
    QString N;
    QString code;// 城市id
    QString name; // 城市名
    QFile file("C:\\Users\\86151\\Documents\\QT_project\\city.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        // QString code;// 城市id
        // QString name; // 城市名
        while (!in.atEnd())
        {
            QString line = in.readLine();//原始字符串
            QStringList parts = line.split("\t");
            if (parts.size() == 2)
            {
                code = parts[0]; // 城市id
                name = parts[1]; // 城市名
                name.replace("市","");
                if(name == *str)
                {
                   return code;
                }

            }
        }
        file.close();
    }
    // 如果没有找到匹配的城市，返回一个空字符串或默认值
    return QString();
}

QString weather::conversion(QString *str)
{
    QString result;
    QString S;
    S = *str;
    QRegularExpression re("(\\d+℃)");
    QRegularExpressionMatch match = re.match(S);
    if(match.hasMatch())
    {
        result = match.captured(1);
    }
    else
    {
        qDebug() << "不匹配";
    }
    return result;
}

QString weather::airpollution(qlonglong  num)
{
    QString result;
    if(num>=0 && num<=50)
    {
        result = "空气质量:良好";
    }
    else if(num>=51 && num<=100)
    {
        result = "空气质量:适中";
    }
    else if(num>=101 && num<=150)
    {
        result = "空气质量:较差";
    }
    else if(num>=151 && num<=200)
    {
        result = "空气质量:差";
    }
    else if(num>=201 && num<=300)
    {
        result = "空气质量:很差";
    }
    else if(num>=300)
    {
        result = "空气质量:污染严重";
    }
    return result;
}


void weather::weathershowSlot()
{
    QString temp1 = vFore->at(0).high + "~"+ vFore->at(0).low;
    ui->week1->setText(vFore->at(0).week);
    ui->ymd1->setText(vFore->at(0).ymd);
    ui->temp1->setText(temp1);
    ui->weather1->setText(vFore->at(0).type);
    ui->quality1->setText(airpollution(vFore->at(0).aqi));

    QString temp2 = vFore->at(1).high + "~"+ vFore->at(1).low;
    ui->week2->setText(vFore->at(1).week);
    ui->ymd2->setText(vFore->at(1).ymd);
    ui->temp2->setText(temp2);
    ui->weather2->setText(vFore->at(1).type);
    ui->quality2->setText(airpollution(vFore->at(1).aqi));

    QString temp3 = vFore->at(2).high + "~"+ vFore->at(2).low;
    ui->week3->setText(vFore->at(2).week);
    ui->ymd3->setText(vFore->at(2).ymd);
    ui->temp3->setText(temp3);
    ui->weather3->setText(vFore->at(2).type);
    ui->quality3->setText(airpollution(vFore->at(2).aqi));

    QString temp4 = vFore->at(3).high + "~"+ vFore->at(3).low;
    ui->week4->setText(vFore->at(3).week);
    ui->ymd4->setText(vFore->at(3).ymd);
    ui->temp4->setText(temp4);
    ui->weather4->setText(vFore->at(3).type);
    ui->quality4->setText(airpollution(vFore->at(3).aqi));

    QString temp5 = vFore->at(4).high + "~"+ vFore->at(4).low;
    ui->week5->setText(vFore->at(4).week);
    ui->ymd5->setText(vFore->at(4).ymd);
    ui->temp5->setText(temp5);
    ui->weather5->setText(vFore->at(4).type);
    ui->quality5->setText(airpollution(vFore->at(4).aqi));

    QString temp6 = vFore->at(5).high + "~"+ vFore->at(5).low;
    ui->week6->setText(vFore->at(5).week);
    ui->ymd6->setText(vFore->at(5).ymd);
    ui->temp6->setText(temp6);
    ui->weather6->setText(vFore->at(5).type);
    ui->quality6->setText(airpollution(vFore->at(5).aqi));

    QString temp7 = vFore->at(6).high + "~"+ vFore->at(6).low;
    ui->week7->setText(vFore->at(6).week);
    ui->ymd7->setText(vFore->at(6).ymd);
    ui->temp7->setText(temp7);
    ui->weather7->setText(vFore->at(6).type);
    ui->quality7->setText(airpollution(vFore->at(6).aqi));

    ui->fx->setText(vFore->at(0).fx);
    ui->fl->setText((vFore->at(0).fl));

    QString str1 = QString("select * from city where cityname = '%1' and cityid = '%2'").arg(ct.city).arg(ct.citykey);
    QSqlQuery *query1 = this->cityDatabase->execSql(str1);
    if(query1 && !query1->next())
    {
        ui->pushButton_2->setStyleSheet("border-image: url(:/klove.png);");
    }
    else
    {
        ui->pushButton_2->setStyleSheet("border-image: url(:/love.png);");
    }
}

void weather::finishedSlot(QNetworkReply *reply)
{
    //通过应答对象获得网络状态码(HttpStatusCode),一般200代表成功
    QVariant code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    int ret = code.toInt();
    if(ret == 200)
    {
        qDebug() << "请求网页成功";
        QByteArray byteArr = reply->readAll();
        // qDebug() << byteArr.toStdString().c_str();
        parsejson(byteArr);//把网络发来的数据进行解析
    }
    else
    {
        qDebug() << "请求网页失败" << ret;
    }
}

void weather::on_pushButton_clicked()
{
    vFore->clear();
    QString str = ui->lineEdit->text();
    ui->lineEdit->clear();
    QNetworkRequest nr(QUrl(QString("http://t.weather.sojson.com/api/weather/city/%1").arg(findCityid(&str))));
    Manager->get(nr);
}

void weather::on_comboBox_currentTextChanged(const QString &arg1)
{
    QString cityname = arg1;
    QString citycode = findCityid(&cityname);
    qDebug() << citycode;
    vFore->clear();
    QNetworkRequest nr(QUrl(QString("http://t.weather.sojson.com/api/weather/city/%1").arg(citycode)));
    Manager->get(nr);
}

//关注城市按钮
void weather::on_pushButton_2_clicked()
{
    if(ct.city.isNull())
    {
        QMessageBox::about(this,"提示","当前不能关注");
        return;
    }
    QString sql1 = QString("select * from city where cityname = '%1' and cityid = '%2'").arg(ct.city).arg(ct.citykey);
    QString sql2 = QString("insert into city(cityname,cityid) values ('%1','%2')").arg(ct.city).arg(ct.citykey);
    QString sql3 = QString("DELETE FROM city WHERE cityid = '%1'").arg(ct.citykey);
    QSqlQuery *query1 = this->cityDatabase->execSql(sql1);
    if(query1 && !query1->next())
    {
        QMessageBox::about(this,"提示","关注成功");
        ui->pushButton_2->setStyleSheet("border-image: url(:/love.png);");
        ui->pushButton_2->setText("已关注");
        this->cityDatabase->execSql(sql2);
    }
    else
    {
        QMessageBox::about(this,"提示","已取消关注");
        ui->pushButton_2->setStyleSheet("border-image: url(:/klove.png);");
        ui->pushButton_2->setText("关注");
        this->cityDatabase->execSql(sql3);
    }
    emit finishedfollow();
}

void weather::comboxshow()
{
    // 假设你已经创建了数据库连接并准备好执行查询
    QSqlQuery *query = this->cityDatabase->execSql("SELECT * FROM city ORDER BY id DESC");  // 查询语句

    if (this->cityDatabase->execSql("SELECT * FROM city ORDER BY id DESC")) {
        // 清空 QComboBox，确保不重复添加数据
        ui->comboBox->clear();


        // 遍历查询结果并添加到 QComboBox
        while (query->next()) {
            QString cityName = query->value("cityname").toString();
            ui->comboBox->addItem(cityName);
        }
    } else {
        // 查询失败时输出错误信息
        qDebug() << "Query failed:" << query->lastError().text();
    }
}

